<template>
  <div>
		<div class="login-container">
			<el-form ref="loginForm" :model="loginForm"  class="login-form" auto-complete="on" label-position="left">
				<h3 class="title">尘缘订单管理系统</h3>
				<el-form-item prop="username">
					<span class="svg-container">
						<svg-icon icon-class="user" />
					</span>
					<el-input v-model="loginForm.username" name="username" type="text" auto-complete="on" placeholder="user_id" />
				</el-form-item>
				<el-form-item prop="password">
					<span class="svg-container">
						<svg-icon icon-class="password" />
					</span>
					<el-input
						:type="pwdType"
						v-model="loginForm.password"
						name="password"
						auto-complete="on"
						placeholder="password"
						@keyup.enter.native="userlogin" />
					<span class="show-pwd" @click="showPwd">
						<svg-icon :icon-class="pwdType === 'password' ? 'eye' : 'eye-open'" />
					</span>
				</el-form-item>
				<el-form-item>
					<el-button :loading="loading" type="primary" style="width:100%;background: #67C23A;" @click.native.prevent="userlogin">
						登录
					</el-button>
				</el-form-item>
				<el-form-item>
					<el-button :loading="loading" type="primary" style="width:100%;" @click.native.prevent="test">
						注册
					</el-button>
				</el-form-item>
			</el-form>
		</div>
		
		<el-dialog :title="text" :visible.sync="dialogUpdate">
			<el-form :model="form" :rules="formRules">
				<el-form-item label="客户编码：" prop="user_id">
					<el-input :disabled="iseditor" v-model="form.user_id"></el-input>
				</el-form-item>
				<el-form-item label="客户名称：" prop="user_name">
					<el-input v-model="form.user_name"></el-input>
				</el-form-item>
				<el-form-item label="性别：" prop="sex">
					<el-radio-group v-model="form.sex">
						<el-radio label="1">男</el-radio>
						<el-radio label="2">女</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="手机：" prop="tel">
					<el-input v-model="form.tel" :maxlength="11" @change="checkNo(form.tel)" type = "text" onkeypress="return event.keyCode>=48&&event.keyCode<=57"></el-input>
				</el-form-item>
				<el-form-item label="密码：" prop="password">
					<el-input v-model="form.password" type="password"></el-input>
				</el-form-item>
				<el-form-item label="地址：" prop="address">
					<el-input v-model="form.address"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer" >
				<el-button @click="dialogUpdate = false">取 消</el-button>
				<el-button type="primary" @click="updateButton">确 定</el-button>
			</div>
		</el-dialog>
  </div>
</template>

<script>
import { isvalidUsername } from '@/utils/validate'
import Cookies from 'js-cookie'
import {selectalluser} from '../../api/user.js'
import {createuser} from '../../api/user.js'

export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!isvalidUsername(value)) {
        callback(new Error('请输入正确的用户编号'))
      } else {
        callback()
      }
    }
    const validatePass = (rule, value, callback) => {
      if (value.length < 5) {
        callback(new Error('密码不能小于5位'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        username: '',
        password: ''
      },
			formRules:{
				user_id: [
				    { required: true, message: '请输入客户', trigger: 'change' },
			    ],
			    user_name: [
				     { required: true, message: '请输入用户名', trigger: 'change' },
			    ],
				sex:[
			        { required: true, message: '请选择性别', trigger: 'change' },
			    ],
			    tel:[
			        { required: true, message: '请输入联系方式', trigger: 'change' },
			    ],
				password:[
				    { required: true, message: '请输入密码', trigger: 'change' },
				],
			    address:[
			    	 { required: true, message: '请输入地址', trigger: 'change' }
			    ]
			},
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePass }]
      },
      loading: false,
      pwdType: 'password',
      redirect: undefined,
			userData:[],
			usertemp:[],
			form: {
				user_id: '',
				user_name: '',
				sex: '',
				tel: '',
				password: '',
				address: ''
			},
			dialogUpdate: false,
			iseditor:true,
			text: '',
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  methods: {
		checkNo(value){
			let reg = /^[1-9]\d*$/;
			if (value) {
				if ( new RegExp(reg).test(value) == false) {
					setTimeout(() => {
						this.form.tel ='';
			         }, 500);
				}
			}
		},
		get_userList() {
			this.userData = [];
			this.usertemp = [];
			selectalluser().then(response => {
				// console.log(response, 'response22');
				this.userData = response;
				for(let i=0;i<this.userData.length;i++){
					if(this.usertemp.indexOf(this.userData[i].user_id)<0){
						this.usertemp.push(this.userData[i].user_id);
					}
				}
			})
		},
		userlogin(){
				if(this.loginForm.username == ''){
					this.$notify({
					  title: '警告',
					  message: '请填写用户名',
					  type: 'info',
					})
					return ;
				}
				if(this.loginForm.password == ''){
					this.$notify({
					  title: '警告',
					  message: '请填写密码',
					  type: 'info',
					})
					return ;
				}
				if(this.usertemp.indexOf(this.loginForm.username)<0){
							this.$notify({
						  title: '警告',
						  message: '没有这个用户',
						  type: 'info',
						}) 
						return ;
				}
				for(let i=0;i<this.userData.length;i++){
					if(this.loginForm.username === this.userData[i].user_id){
						if(this.loginForm.password !== this.userData[i].password){
								this.$notify({
								  title: '警告',
								  message: '密码错误',
								  type: 'info',
								})
						}else{
							var user = null;
							user =this.userData[i];
							localStorage.setItem("userInfo",JSON.stringify(user));
							if(user.u_type == '1'){
								Cookies.set("Admin-Token", "admin-token")
								this.$store.commit('SET_TOKEN', "admin-token")
							}else{
								Cookies.set("Admin-Token", "editor-token")
								this.$store.commit('SET_TOKEN', "editor-token")
							}
							this.$router.push({ path: '/' })
							break;
						}
					
					}
				}
		},
		test(){
			this.dialogUpdate = true;
			this.iseditor = false;
			this.text = '新增客户';
			this.form.user_id = '';
			this.form.user_name = '';
			this.form.sex = '';
			this.form.tel = '';
			this.form.password = '';
			this.form.address = '';
// 			Cookies.set("Admin-Token", "admin-token")
// 			this.$store.commit('SET_TOKEN', "admin-token")
//       this.$router.push({ path: this.redirect || '/' })
		},
		updateButton() {
				if(this.form.user_id == '' || this.form.user_name == '' || this.form.sex == '' || this.form.tel == '' || this.form.password == '' || this.form.address == ''){
					this.$notify({
					  title: '警告',
					  message: '请填写完整信息',
					  type: 'info',
					})
					return ;
				}
				for(let i=0;i<this.userData.length;i++){
					if(this.form.user_id == this.userData[i].user_id){
						 this.$notify({
							  title: '警告',
							  message: '用户id已存在',
							  type: 'info',
							})
							return ;
					}
				}
				createuser(this.form).then(() => {
				  this.$notify({
				    title: '成功',
				    message: '创建成功',
				    type: 'success',
				    duration: 2000
				  })
				})
			
			this.dialogUpdate = false;
		},
    showPwd() {
      if (this.pwdType === 'password') {
        this.pwdType = ''
      } else {
        this.pwdType = 'password'
      }
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('Login', this.loginForm).then(() => {
            this.loading = false;
						var user = {"name":"admin","pwd":"admin"}
						localStorage.setItem("userInfo",JSON.stringify(user));
						this.$store_2.state.setusername('admin');
						console.log(this.$store_2.state.username,"---------------------")
            this.$router.push({ path: this.redirect || '/' })
          }).catch(() => {
            this.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  },
	created(){
		this.get_userList();
	}
}
</script>

<style rel="stylesheet/scss" lang="scss">
$bg:#2d3a4b;
$light_gray:#eee;

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;
    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      &:-webkit-autofill {
        -webkit-box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: #fff !important;
      }
    }
  }
  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}

</style>

<style rel="stylesheet/scss" lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;
.login-container {
  position: fixed;
  height: 100%;
  width: 100%;
  background-color: $bg;
  .login-form {
    position: absolute;
    left: 0;
    right: 0;
    width: 520px;
    max-width: 100%;
    padding: 35px 35px 15px 35px;
    margin: 120px auto;
  }
  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;
    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }
  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }
  .title {
    font-size: 26px;
    font-weight: 400;
    color: $light_gray;
    margin: 0px auto 40px auto;
    text-align: center;
    font-weight: bold;
  }
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
